package www.yingdi365.com.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.zhy.magicviewpager.transformer.ScaleInTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseNotLeftActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.fragment.QingJianBJYLFragment;
import www.yingdi365.com.model.AppInvitation;
import www.yingdi365.com.model.AppInvitationSave;
import www.yingdi365.com.model.AppInvitationSaveResult;
import www.yingdi365.com.model.AppMusic;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.model.QingJian;
import www.yingdi365.com.model.QingJianBean;
import www.yingdi365.com.model.XiuGaiQJWZ;
import www.yingdi365.com.util.DpUtils;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.util.ScreenUtils;

public class BianJiQJYLActivity extends ZjbBaseNotLeftActivity implements View.OnClickListener {
    private ViewPager id_viewpager;
    private TextView textViewRight;
    private String id;
    private List<QingJianBean> qingJianBeanList = new ArrayList<>();
    public AppInvitation appInvitation;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.BROADCASTCODE.QingJianBaoCun:
                    int positionGG = intent.getIntExtra(Constant.INTENT_KEY.Position, -1);
                    QingJianBean pagesBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
                    qingJianBeanList.set(positionGG, pagesBean);
                    qingJian.setFirst(qingJianBeanList.get(0));
                    qingJian.setLast(qingJianBeanList.get(qingJianBeanList.size() - 1));
                    qingJian.getMiddles().clear();
                    for (int i = 1; i < qingJianBeanList.size() - 1; i++) {
                        qingJian.getMiddles().add(qingJianBeanList.get(i));
                    }
                    LogUtil.LogShitou("BianJiQJYLActivity--编辑后的请柬对象", "" + GsonUtils.parseObject(qingJian));
                    appInvitation.setRenderData(GsonUtils.parseObject(qingJian));
                    baoCunQingJian();
                    break;
                case Constant.BROADCASTCODE.XiuGaiQJWZ:
                    XiuGaiQJWZ xiuGaiQJWZ = (XiuGaiQJWZ) intent.getSerializableExtra(Constant.INTENT_KEY.XiuGaiQJWZ);
                    appInvitation.setBoy(xiuGaiQJWZ.getBoy());
                    appInvitation.setBoyMobile(xiuGaiQJWZ.getBoyMobile());
                    appInvitation.setGirl(xiuGaiQJWZ.getGirl());
                    appInvitation.setGirlMobile(xiuGaiQJWZ.getGirlMobile());
                    appInvitation.setTreatDate(xiuGaiQJWZ.getTreatDate());
                    appInvitation.setHotel(xiuGaiQJWZ.getHotel());
                    appInvitation.setTreatAddress(xiuGaiQJWZ.getTreatAddress());
                    appInvitation.setTreatAddressLocation(xiuGaiQJWZ.getTreatAddressLocation());
                    QingJianBean qingJianBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
                    qingJianBeanList.set(0, qingJianBean);
                    qingJian.setFirst(qingJianBean);
                    initQingJianBeanList();
                    baoCunQingJian();
                    break;
                case Constant.BROADCASTCODE.XiuGaiYY:
                    AppMusic music = (AppMusic) intent.getSerializableExtra(Constant.INTENT_KEY.music);
                    appInvitation.setMusic(music);
                    baoCunQingJian();
                    break;
                case Constant.BROADCASTCODE.XiuGaiQJSX:
                    String qingJian = intent.getStringExtra(Constant.INTENT_KEY.QingJian);
                    appInvitation.setRenderData(qingJian);
                    initQingJianBeanList();
                    initViewPager();
                    baoCunQingJian();
                    break;
            }
        }

        private OkObject getOkObject1() {
            String url = Constant.HOST + Constant.Url.AppInvitationService + "invitation/save";
            HttpHeaders headers = new HttpHeaders();
            headers.put(Constant.TOKEN, appLoginResult.getToken());
            HashMap<String, String> params = new HashMap<>();
            return new OkObject(headers, params, url);
        }

        private void baoCunQingJian() {
            AppInvitationSave appInvitationSave = new AppInvitationSave(
                    appInvitation.getUuid(),
                    appInvitation.getBoy(),
                    appInvitation.getBoyMobile(),
                    appInvitation.getGirl(),
                    appInvitation.getGirlMobile(),
                    appInvitation.getHotel(),
                    appInvitation.getId(),
                    appInvitation.getMusic(),
                    appInvitation.getName(),
                    appInvitation.getRenderData(),
                    appInvitation.getTmpl(),
                    appInvitation.getTreatAddress(),
                    appInvitation.getTreatAddressLocation(),
                    appInvitation.getTreatDate(),
                    appInvitation.getType());
            showLoadingDialog();
            OkObject okObject = getOkObject1();
            OkGo.post(okObject.getUrl())//
                    .tag(this)//
                    .headers(okObject.getHeaders())
                    .upJson(GsonUtils.parseObject(appInvitationSave))//
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            cancelLoadingDialog();
                            LogUtil.LogShitou("SheZhiYYActivity--设置音乐", "" + s);
                            try {
                                AppInvitationSaveResult appInvitationSaveResult = GsonUtils.parseJSON(s, AppInvitationSaveResult.class);
                                if (appInvitationSaveResult.isSuccess()) {
                                    Toast.makeText(BianJiQJYLActivity.this, appInvitationSaveResult.getMessage(), Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(BianJiQJYLActivity.this, appInvitationSaveResult.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                Toast.makeText(BianJiQJYLActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            cancelLoadingDialog();
                            if (response != null) {
                                if (response.code() == 401) {
                                    showReLoginDialog();
                                }
                            }
                            Toast.makeText(BianJiQJYLActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    };

    private void initViewPager() {
        id_viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        id_viewpager.setPageMargin((int) DpUtils.convertDpToPixel(20f, BianJiQJYLActivity.this));
        id_viewpager.setOffscreenPageLimit(3);
        id_viewpager.setPageTransformer(true, new ScaleInTransformer());
    }

    private void initQingJianBeanList() {
        qingJian = GsonUtils.parseJSON(appInvitation.getRenderData(), QingJian.class);
        qingJianBeanList.clear();
        qingJianBeanList.add(qingJian.getFirst());
        qingJianBeanList.addAll(qingJian.getMiddles());
        qingJianBeanList.add(qingJian.getLast());
    }

    private QingJian qingJian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bian_ji_qjyl);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        id = intent.getStringExtra(Constant.INTENT_KEY.ID);
    }

    @Override
    protected void findID() {
        id_viewpager = (ViewPager) findViewById(R.id.id_viewpager);
        textViewRight = (TextView) findViewById(R.id.textViewRight);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.textViewTitle)).setText("请柬预览");
        textViewRight.setText("发送请柬");
        int screenWidth = ScreenUtils.getScreenWidth(this);
        ViewGroup.LayoutParams layoutParams = id_viewpager.getLayoutParams();
        float width = screenWidth - DpUtils.convertDpToPixel(100f, this);
        layoutParams.width = (int) width;
        layoutParams.height = (int) (width * 1.4375f);
        id_viewpager.setLayoutParams(layoutParams);
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
        findViewById(R.id.viewYeMain).setOnClickListener(this);
        findViewById(R.id.viewYinYue).setOnClickListener(this);
        findViewById(R.id.viewYuLan).setOnClickListener(this);
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.AppInvitationService + "invitation/" + id;
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    @Override
    protected void initData() {
        showLoadingDialog();
        OkObject okObject = getOkObject();
        OkGo.get(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        cancelLoadingDialog();
                        LogUtil.LogShitou("BianJiQJYLActivity--onSuccess获取请柬", s);
                        try {
                            appInvitation = GsonUtils.parseJSON(s, AppInvitation.class);
                            initQingJianBeanList();
                            initViewPager();
                        } catch (Exception e) {
                            Toast.makeText(BianJiQJYLActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        cancelLoadingDialog();
                        if (response != null) {
                            if (response.code() == 401) {
                                showReLoginDialog();
                            }
                        }
                        Toast.makeText(BianJiQJYLActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Constant.REQUEST_RESULT_CODE.XiuGaiQingJian == requestCode && Constant.REQUEST_RESULT_CODE.XiuGaiQingJian == resultCode) {
            initData();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.viewYuLan:
                intent.setClass(this, WebActivity.class);
                intent.putExtra(Constant.INTENT_KEY.TITLE, "预览");
                intent.putExtra(Constant.INTENT_KEY.URL, appInvitation.getHtmlUrl());
                startActivity(intent);
                break;
            case R.id.viewYinYue:
                intent.setClass(this, SheZhiYYActivity.class);
                intent.putExtra(Constant.INTENT_KEY.appInvitation, appInvitation);
                startActivity(intent);
                break;
            case R.id.viewYeMain:
                intent.setClass(this, YeMainTZActivity.class);
                intent.putExtra(Constant.INTENT_KEY.appInvitation, appInvitation);
                startActivity(intent);
                break;
            case R.id.imageBack:
                finish();
                break;
        }
    }

    class MyPagerAdapter extends FragmentStatePagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new QingJianBJYLFragment(qingJianBeanList.get(position), position);
        }

        @Override
        public int getCount() {
            return qingJianBeanList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.QingJianBaoCun);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiQJWZ);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiYY);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiQJSX);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
